public with sharing virtual class CaseEmailsComponentController {
    
   public Case emailCase {get; set;}

   public Id emailId  {get; set;}   
           
   public Integer recordLimit {get; set;} 
   public cEmail[] caseEmails;
   
   
   private final integer ROWS_PER_LIST = 15;    
   public Map<Integer,String > emailStatus = new Map<Integer,String > { 0=>'New',1=>'Read',2=>'Replied',3=>'Sent',4=>'Forwarded' };
   
   private cEmail caseEmail;
   public cEmail getcaseEmail() {
     return caseEmail;
   }
   
   public CaseEmailsComponentController()
   {
       if (recordLimit== null){ recordLimit = 100; }
      
       
   }
   //get more rows per list for email attachment list
   public integer getMoreRowsperlist()
   {
   	    integer rowsperlist = getRowsperList(0);
	 	if ( rowsperlist != 0)  
	        return  rowsperlist + 5;
	     else
	        return ROWS_PER_LIST * 2;
   } 
   
   //get fewer rows per list for email attachment list
   public integer getFewRowsperlist()
   {
   	     integer rowsperlist = getRowsperList(0);
	   	 if ( rowsperlist > 15)  
	       return rowsperlist - 5;
	     else
	        return ROWS_PER_LIST;
   	
   }
   
   //parse rowsperlist querystring 
   private integer getRowsperList(integer defaultValue)
   {   	     	
	   try {
	   	    if ( ApexPages.currentPage().getParameters().get('rowsperlist') != null)   {
	   	        integer recordsperList =  integer.valueof(ApexPages.currentPage().getParameters().get('rowsperlist'));
	     	    return recordsperList;
	   	    }
	     	 else{	     	 
	     	      return defaultValue;
	     	 }
	     	         
	   }	   
	   catch( System.Typeexception ex )  {
	   	   return defaultValue;	   	   
	   }
        
   }
   //get  list of email attachments for the email message
   public List<cAttachment> getEmailAttachments()
   {
     	   list<cAttachment> attachments = new list<cAttachment>();
     	   
     	   integer rowperlist= getRowsperList(15);
     	      
           for(Attachment attach: [Select Id, BodyLength, LastModifiedById, LastModifiedDate, Name, OwnerId, Owner.Name from Attachment where parentid = :ApexPages.currentPage().getParameters().get('id') order by LastModifiedDate desc LIMIT :rowperlist])
           {
    	         cAttachment tempcAttach	= new cAttachment();	
	             tempcAttach.attachId 		= attach.Id;
	             tempcAttach.fileName 		= attach.Name;
	             tempcAttach.size 			= attach.BodyLength;
	             tempcAttach.lastModified 	= attach.LastModifiedDate.format();
	             tempcAttach.createdBy		= attach.Owner.Name;
	             tempcAttach.createdById	= attach.OwnerId;
	    
	             attachments.add(tempcAttach);
           }
           if(attachments.size() > 0 )
               return attachments;
           else
               return null;    
   }
    //get list of email messages           
    public virtual List<cEmail> getCaseEmailMessage(){        
       
         
           list<cEmail> caseEmails = new list<cEmail>();
           for(EmailMessage email : [Select Id, MessageDate, Status, Subject, ToAddress, Incoming,TextBody,HtmlBody,HasAttachment From EmailMessage  where parentid = :emailCase.Id order by LastModifiedDate desc LIMIT :recordLimit ])
           {
             cEmail tempcEmail= new cEmail();
             tempcEmail.emailId 	= email.Id;
             tempcEmail.status		= emailStatus.get(integer.valueof(email.Status));
             tempcEmail.subject		= email.subject;
             tempcEmail.toaddress	= email.toaddress;
             if(email.messageDate!= null )
                tempcEmail.messageDate	= email.messageDate.format();
                
             tempcEmail.hasAttachment = email.HasAttachment;
             if(email.TextBody != null)   { 
	             if( email.TextBody.Length()> 80)
	                 tempcEmail.Body 	= email.TextBody.SubString(0,77) + '...';
	             else
	                tempcEmail.Body 	= email.TextBody;
	              
              }
             else
                {
	             if(email.HtmlBody != null && email.HtmlBody.Length()> 80)
	                 tempcEmail.Body 	= email.HtmlBody.SubString(0,77) + '...';
	             else
	                tempcEmail.Body 	= email.HtmlBody;
                
                }   
       	     tempcEmail.Incoming	= email.Incoming;
			 //Add to list              
             caseEmails.add(tempcEmail);
           }
          
           if(caseEmails.size() == 0 ) 
              return null;
           else 
              return caseEmails;
        }   
    
    //get the email details          
    public void ViewData(){        
    	             
             EmailMessage email = 
                 [Select Id, ParentId, Parent.CaseNumber, ToAddress, BccAddress, CcAddress, CreatedById, CreatedBy.Name, CreatedDate, FromAddress, FromName, HasAttachment, LastModifiedById, LastModifiedBy.Name, LastModifiedDate,  MessageDate, Status, Subject, Incoming, TextBody, HtmlBody From EmailMessage  where id = :ApexPages.currentPage().getParameters().get('id')];
                 
             cEmail tempcEmail			= new cEmail();
             tempcEmail.emailId 		= email.Id;             
             tempcEmail.caseNumber 		= email.Parent.CaseNumber;
             tempcEmail.status			= emailStatus.get(integer.valueof(email.Status));
             tempcEmail.subject			= email.subject;
             tempcEmail.toaddress		= email.toaddress;
             
			 if(email.messageDate!= null )
               tempcEmail.messageDate		= email.messageDate.format();
               
             tempcEmail.createdDate		= email.createdDate.format();
             tempcEmail.modifiedDate	= email.LastModifiedDate.format();
             
             tempcEmail.body 			= GetHTMLDisplayEmailBody(email.HtmlBody,email.TextBody);
             tempcEmail.createdByName	= email.CreatedBy.Name;
             tempcEmail.createdByID     = email.CreatedByid;
             tempcEmail.modifiedByName	= email.LastModifiedBy.Name;
             tempcEmail.modifiedByID     = email.LastModifiedByid;
             tempcEmail.fromAddress		= email.FromAddress;
             tempcEmail.fromName		= email.FromName;
             tempcEmail.toAddress		= email.ToAddress;
             tempcEmail.ccAddress		= email.CCAddress;
             tempcEmail.bccAddress		= email.BCCAddress;
             tempcEmail.parentCaseId 	= email.ParentId;
			 tempcEmail.Incoming		= email.Incoming;
			 tempcEmail.hasAttachment 	= email.HasAttachment;
             if(email.Incoming)
                tempcEmail.subtitle =  'Inbound Email Message';
             else
                tempcEmail.subtitle =  'Outbound Email Message';
                
             	//get the previous and next email details
        	    string prevEmailId ;
    	        string nextEmailId ;
             
	            List<EmailMessage> allEmails = [Select Id From EmailMessage where parentid = :email.ParentId order by LastModifiedDate desc];
	            
	            if( allEmails.Size() > 1)  { //only if there are more than one items..
	             	for (Integer i = 0; i < allEmails.Size(); i++) {
						  if(allEmails[i].Id == email.Id)	  {
						  	if(i < allEmails.Size() - 1)  prevEmailId = allEmails[i+1].Id;
	             	   		if(i > 0)  nextEmailId = allEmails[i-1].Id;					  
						  }
             	}			 
             }         
             tempcEmail.prevEmailId 	= prevEmailId;
             tempcEmail.nextEmailId 	= nextEmailId;
             
             caseEmail= tempcEmail;
                                  
        }
            
  private string GetHTMLDisplayEmailBody(string htmlBody,string textBody)
  {
  	   //if no text body 
        if(textBody == null)
             return htmlBody;
        else
             return textBody.replaceAll('\n', '<br>');
             //return textBody;
  }
  
  //Get New Email page link  
  public PageReference  NewEmail()  {   
    string newEmailLink = '/apex/SendAnEmailPage?id=' + emailCase.Id ;        
    PageReference pageRef= new PageReference(newEmailLink);
    pageRef.setredirect(true);
    return pageRef;
    
   }
   
//delete the selected email message    
   public PageReference deleteEmailMessage()  {                   
   
   if(emailId != null) {
        EmailMessage caseEmail = new EmailMessage(Id=emailId);      
        delete caseEmail;       
     }  
        // redirect to current page
        PageReference pg =  ApexPages.currentPage();
        pg.setRedirect(true);    
        return pg;
    }    
   //Email Message object 
   public class cEmail {   	    
        public ID emailId {get; set;}
        public ID prevEmailId {get; set;}
        public ID nextEmailId {get; set;}
        public String caseNumber {get; set;}
        public ID parentCaseId {get; set;}
        public string caserecordType {get; set;}
        public string caseOwner {get; set;}
        public string caseStatus  {get; set;}        
        public String status {get; set;}
        public String subject {get; set;}
        public String toaddress {get; set;}
        public String messageDate {get; set;}
        public boolean incoming {get;set;}
        public boolean hasAttachment {get;set;}
        public String body {get;set;} 
        public String createdByName {get;set;}
        public String createdDate {get;set;}
        public ID createdByID {get;set;}        
        public String modifiedByName {get;set;}
        public ID modifiedByID {get;set;}
        public String modifiedDate {get;set;}
     	public String fromAddress {get;set;}
        public String fromName {get;set;}        
        public String ccAddress {get;set;}
        public String bccAddress {get;set;}  
        public String subtitle {get;set;}
        public boolean selectedCase{get;set;}
        
  }
  
  //Attachment object
  public class cAttachment{
	  	public ID attachId {get;set;}
	  	public ID createdById {get;set;}
	  	public string fileName{get;set;}
	  	public integer size{get;set;}
	  	public string lastModified{get;set;}
	  	public string createdBy{get;set;}  		 
  }    
}